import { writable, derived } from "svelte/store";
import { request } from "@/api/request";
import {keyWordListUri} from "@/api/api";
import { toast } from '@/utils/toastService';
// 设置数据源
const state = writable({
  count: 0,
  user: null,
});

const getters = {
  doubleCount: derived(state, ($state) => $state.count * 2),
  isLoggedIn: derived(state, ($state) => !!$state.user),
};
// 处理同步数据
const mutations = {
  /**
   * 为state项赋值
   * @param state
   * @param data
   */
  setStateItem(data) {
    state.update((currentState) => {
      return {
        ...currentState,
        ...data,
      };
    });
  },
};
// 处理异步数据
const actions = {
  async getUserData(params) {
    toast.show('Hello, this is a toast!')
    try {
      const res = await request(keyWordListUri, params,'get');
      console.log(res);
  
      if (res.code === 200) {
        mutations.setStateItem({ user: res.data });
        // 接口成功回掉函数
        params.callback && params.callback(res.data);
      }
    } catch (error) {}
  },
};

export const centerModule = {
  state,
  getters,
  actions,
};
